package service

import (
	"strconv"

	"gitee.com/wao520/obtain_data/dao"
	"gitee.com/wao520/obtain_data/global"
	"github.com/go-redsync/redsync/v4"
	"github.com/go-redsync/redsync/v4/redis/goredis/v8"
)

// 购买一件商品,by lock
func LockBuyOneGoods(goodsId int64, buyNum int) error {

	//fmt.Println("begin LockBuyOneGoods")

	pool := goredis.NewPool(global.RedisDb)
	rs := redsync.New(pool)
	mutexname := "goods_" + strconv.FormatInt(goodsId, 10)
	mutex := rs.NewMutex(mutexname)
	if err := mutex.Lock(); err != nil {
		return err
	}
	errdecre := dao.DecreaseOneGoodsStock(goodsId, buyNum)

	if ok, err := mutex.Unlock(); !ok || err != nil {
		return err
	}

	if errdecre != nil {
		return errdecre
	}

	return nil
}
